package cn.yzx.pethome.system.login.controller;

import cn.yzx.pethome.config.WxConfig;
import cn.yzx.pethome.constants.BaseConstants;
import cn.yzx.pethome.system.login.domain.PhoneRegister;
import cn.yzx.pethome.system.login.domain.WechatBinder;
import cn.yzx.pethome.system.login.domain.WechatCode;
import cn.yzx.pethome.system.logininfo.domain.LoginRo;
import cn.yzx.pethome.system.logininfo.service.ILogininfoService;
import cn.yzx.pethome.system.user.domain.User;
import cn.yzx.pethome.system.user.service.IUserService;
import cn.yzx.pethome.system.wxuser.domain.Wxuser;
import cn.yzx.pethome.system.wxuser.service.IWxuserService;
import cn.yzx.pethome.utils.AjaxResult;
import cn.yzx.pethome.utils.BusinessException;
import cn.yzx.pethome.utils.HttpClientUtils;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.httpclient.HttpClient;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/login")
@Api(value = "登录API" , description = "登录的功能")
public class LoginController {
    @Autowired
    private WxConfig wxConfig;
    @Autowired
    private IWxuserService wxuserService;
    @Autowired
    public ILogininfoService logininfoService;
    @Autowired
    private IUserService userService;
    @Autowired
    private RedisTemplate redisTemplate;



    /**
     * 1.获取到授权码
     * 2.拼接获取令牌的地址
     * 3.发送请求-接收返回的数据(获取得到令牌)
     * 3.1 根据获取到的unionid  去查询数据判断有没有数据
     * 如果没有  3.1.1 就发送请求获取当前用户的信息，保存到数据库中(后续需要继续绑定账号)
     * 如果有    3.1.2 并且user_id 有值，直接登录成功；如果没有user_id，跳转绑定账号页面
     * 4.拿到令牌获取用户信息
     *
     * @return
     */

    @ApiOperation(value = "微信登录的接口")
    @PostMapping("/wechat")
    public AjaxResult wechat(@RequestBody WechatCode wechatCode) {
        String code = wechatCode.getCode();
        if (code == null) {
            throw new BusinessException("非法访问！");
        }
        String url = wxConfig.getAccessTokenUrl(code);
        //导入一个工具类 发送get请求
        String result = HttpClientUtils.httpGet(url);//这里得到的是json字符串
        //将json字符串转换为对象  当成map使用
        JSONObject jsonObject = JSONObject.parseObject(result);
        String access_token = jsonObject.getString("access_token");
        String unionid = jsonObject.getString("unionid");
        String openid = jsonObject.getString("openid");
        if ("".equals(access_token) || access_token == null) {
            throw new BusinessException("非法访问！");
        }

        Wxuser wxuser = wxuserService.findByUnionid(unionid);
        //如果wxuser等于空，那么表示用户第一次进来
        if (wxuser == null) {
            //获取用户信息进行保存
            String userinfoUrl = wxConfig.getUserinfoUrl(access_token, openid);
            String userInfoResult = HttpClientUtils.httpGet(userinfoUrl);
            Wxuser wxuserResult = JSONObject.parseObject(userInfoResult, Wxuser.class);
            wxuserService.add(wxuserResult);
            //跳转绑定页面
            //todo
            return AjaxResult.success().setMsg("NoBind").setData(unionid);
        } else {
            //如果获取userId为空 没有绑定用户 则直接跳转绑定页面
            if (wxuser.getUserId() == null) {
                //跳转绑定页面
                //todo
                return AjaxResult.success().setMsg("NoBind").setData(unionid);
            } else {
                //直接跳转登录 完成
                Long userId = wxuser.getUserId();
                User user = userService.findOne(userId);
                LoginRo loginRo = new LoginRo();
                loginRo.setPassword(user.getPassword());
                loginRo.setUsername(user.getUsername());
                loginRo.setType(BaseConstants.Logininfo.STATE_USER);
                loginRo.setAutoLogin(false);
                return logininfoService.account(loginRo);
            }
        }
    }

    @ApiOperation(value = "微信绑定的接口")
    @PostMapping("/wechat/binder")
    public AjaxResult wechatBinder(@RequestBody WechatBinder wechatBinder) {
        //校验手机号、验证码、unionid
        if (wechatBinder.getPhone() == null) {
            throw new BusinessException("手机号不能为空！");
        }
        if (wechatBinder.getVerifyCode() == null) {
            throw new BusinessException("验证码不能为空！");
        }
        if (wechatBinder.getUnionid() == null) {
            throw new BusinessException("非法访问！");
        }
        //手机验证码
        String verifyCode = wechatBinder.getVerifyCode();
        Object obj = redisTemplate.opsForValue().get(wechatBinder.getPhone() + BaseConstants.Vcode.BIND);
        if (obj == null) {
            throw new BusinessException("验证码已过期！");
        }
        String s = obj.toString();
        if (!s.equals(verifyCode)) {
            throw new BusinessException("验证码输入错误！");
        }
        //验证手机号是否被注册
        User byPhone = userService.findByPhone(wechatBinder.getPhone());
        if (byPhone != null) {
            Wxuser byUserid = wxuserService.findByUserid(byPhone.getId());
            if (byUserid != null) {//被绑定了
                throw new BusinessException("该手机号已被绑定了！");
            } else {//没有被绑定
                executeBind(wechatBinder, byPhone);
            }
        } else {
            PhoneRegister phoneRegister = new PhoneRegister();
            phoneRegister.setPhone(wechatBinder.getPhone());
            phoneRegister.setPassword("111111"); //我们设置的默认密码
            Long userid = userService.add(phoneRegister);
            byPhone = new User();
            //给当前手机号发送短信，告诉用户默认密码，并提示他修改

            byPhone.setId(userid);
            executeBind(wechatBinder, byPhone);
            byPhone.setUsername(wechatBinder.getPhone());
            byPhone.setPassword(phoneRegister.getPassword());
        }
        LoginRo loginRo = new LoginRo();
        loginRo.setPassword(byPhone.getPassword());
        loginRo.setUsername(byPhone.getUsername());
        loginRo.setType(BaseConstants.Logininfo.STATE_USER);
        loginRo.setAutoLogin(false);
        return logininfoService.account(loginRo);
    }
    private void executeBind(WechatBinder wechatBinder, User byPhone){
        Wxuser byUnionid = wxuserService.findByUnionid(wechatBinder.getUnionid());
        if (byUnionid == null) {
            throw new BusinessException("非法访问！");
        }
        //保存用户信息
        byUnionid.setUserId(byPhone.getId());
        wxuserService.update(byUnionid);
    }
}
